import 'dart:io';

import 'package:flutter/material.dart';
import 'package:giwiki/components/alert_dialog.dart';
import 'package:giwiki/cross.dart' as cross;
import 'package:giwiki/screens/settings.dart';
import 'package:giwiki/src/rust/api/api.dart' as api;

import '../components/confirm_dialog.dart';
import '../components/toast.dart';
import '../entities/entities_data.dart';

class InitScreen extends StatefulWidget {
  const InitScreen({super.key});

  @override
  State<StatefulWidget> createState() => _InitScreenState();
}

class _InitScreenState extends State<InitScreen> {
  var _text = "初始化中...";

  @override
  void initState() {
    super.initState();
    _initApplication();
  }

  void _setText(String text) {
    setState(() {
      _text = text;
    });
  }

  Future _initApplication() async {
    await cross.initRoot();
    await initColumnCountSetting();
    var repoState = await api.repoState();
    if (repoState == "CLEAN") {
      await for (var value in api.repoPull()) {
        setState(() {
          _text = value;
        });
      }
      if (_text != "OK") {
        toast(context, "未能拉取最新数据");
      }
      try {
        await buildCacheAndGoHome(context, _setText);
      } catch (e, s) {
        print("$e\n$s");
        await alert(
          context,
          title: const Text('初始化失败'),
          content: const Text('请尝试升级应用或者联系开发者'),
          textOK: const Text('退出'),
        );
        exit(0);
      }
    } else if (repoState == "NotExists") {
      final result = await confirm(
        context,
        title: const Text('数据库未找到'),
        content: const Text(
          '从互联网下载数据库吗？这将会下载大量的媒体, 请确保您的设备有足够的存储空间以及稳定的互联网连接。',
        ),
        textOK: const Text('下载数据'),
        textCancel: const Text('退出应用'),
        canPop: false,
      );
      if (result) {
        if (Platform.isIOS || Platform.isAndroid) {
          cross.mobile.setKeepScreenOn(true);
        }
        var sk = api.reClone();
        await for (var value in sk) {
          setState(() {
            _text = value;
          });
        }
        if (Platform.isIOS || Platform.isAndroid) {
          cross.mobile.setKeepScreenOn(false);
        }
        if (_text == "OK") {
          try {
            await buildCacheAndGoHome(context, _setText);
          } catch (e, s) {
            print("$e\n$s");
            await alert(
              context,
              title: const Text('初始化失败'),
              content: const Text('请尝试升级应用或者联系开发者'),
              textOK: const Text('退出'),
            );
            exit(0);
          }
        }
      } else {
        exit(0);
      }
    } else {}
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          _background(),
          _progress(),
        ],
      ),
    );
  }

  Widget _progress() {
    var padding = MediaQuery.of(context).size.height / 5;
    return SafeArea(
      child: Align(
        alignment: Alignment.bottomCenter,
        child: Container(
          color: Colors.black.withAlpha(100),
          padding: EdgeInsets.only(
            left: 30,
            right: 30,
            bottom: padding,
          ),
          child: Text(
            _text,
            style: const TextStyle(color: Colors.white),
          ),
        ),
      ),
    );
  }

  Widget _background() {
    return Padding(
      padding: const EdgeInsets.all(10),
      child: Center(
        child: Image.asset(
          "lib/assets/splash.png",
          fit: BoxFit.contain,
        ),
      ),
    );
  }
}
